<template>
    <div class="page-controller">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="item.label" :name="item.id" v-for="item,index in tabsArr" :key="index"></el-tab-pane>
      </el-tabs>
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        v-model:form-value="state.query"
        :table-column="columns"
        :wrapperSpan="8"
        @submit="searchFn"
        :exclude-values="exclueValues"
      >
        <el-col :span="8" v-if="activeName == '1'">
          <FIFormItem prop="appId" label="应用ID">
            <FIInput v-model="state.query.appId" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '1'">
          <FIFormItem prop="appCode" label="应用代码">
            <FIInput v-model="state.query.appCode" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '1'">
          <FIFormItem prop="appName" label="应用名称">
            <FIInput v-model="state.query.appName" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '2'">
          <FIFormItem prop="appId" label="应用ID">
            <FIInput v-model="state.query.appId" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '2'">
          <FIFormItem prop="moduleId" label="模块ID">
            <FIInput v-model="state.query.moduleId" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '2'">
            <FIFormItem prop="moduleCode" label="模块代码">
                <FIInput v-model="state.query.moduleCode" clearable />
            </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '2'">
            <FIFormItem prop="moduleName" label="模块名称">
                <FIInput v-model="state.query.moduleName" clearable />
            </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '3'">
          <FIFormItem prop="appCode" label="应用ID">
            <FIInput v-model="state.query.appCode" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '3'">
          <FIFormItem prop="biztypeId" label="业务类型ID">
            <FIInput v-model="state.query.biztypeId" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '3'">
            <FIFormItem prop="biztypeCode" label="业务类型代码">
                <FIInput v-model="state.query.biztypeCode" clearable />
            </FIFormItem>
        </el-col>
        <el-col :span="8" v-if="activeName == '3'">
            <FIFormItem prop="biztypeName" label="业务类型名称">
                <FIInput v-model="state.query.biztypeName" clearable />
            </FIFormItem>
        </el-col>
        
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        v-if="activeName == '1'"
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="id"
        :rowNo="true"
        v-model:columns="columns"
        :insertable="true" 
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @row-add-save="addRowSave"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
      >
        <template #headerBtn>
            <!-- <el-button type="primary" @click="deleteRow">删除</el-button> -->
            <FIPopconfirmBtn
              title="您是否确认删除选中数据吗？"
              buttonText="删除"
              beforePopText="请选择一条数据"
              :btn-binds="{ id: 'delete', border: true }"
              @confirm="deleteRow"
              style="margin-right:10px;"
            >
            </FIPopconfirmBtn>
            <FIButton id="import" border @click="importDiag = true"></FIButton>
            <FIButton id="export" border @click="exportClick('app')"></FIButton>
        </template>
        <template #platType="{scope}">
          <FISelect
            v-if="scope.row.isSelected"
            v-model="scope.row.platType"
            valueCustom="value"
            :options="[
              { value: 'iplat4jV6', label: 'iplat4j V6' },
              { value: 'iplat4jV3.9', label: 'iplat4j V3.9' },
              { value: 'other', label: '其他' },
            ]"
            clearable
          />
          <span v-else>{{scope.row.platType == 'other' ? '其他' : scope.row.platType}}</span>
        </template>
      </FITable>
      <module-page v-if="activeName == '2'" :dataList="state.dataList" :pageConfig="pageConfig" @currentChange="handleCurrentChange" @get-list="searchFn" @export-click="exportClick('module')"></module-page>
      <biz-type-page v-if="activeName == '3'" :dataList="state.dataList" :pageConfig="pageConfig" @currentChange="handleCurrentChange" @get-list="searchFn" @export-click="exportClick('biz')"></biz-type-page>
      <FIModel v-model="importDiag" width="500" title="数据权限配置导入" @confirm="uploadSure">
        <FIUpload @upload="uploadFunc"></FIUpload>
      </FIModel>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, toRaw } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import { apiRequestPost } from '@/api/globalApi.js'
  import { ElMessage } from 'element-plus'
  import { useMessage, useMessageBox } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import bizTypePage from './components/bizTypePage'
  import modulePage from './components/modulePage'
  import { apiQueryAuth, apiDeleteAuth,apiQueryApp,apiQueryModule,apiQueryBizType,apiDeleteApp,apiSaveApp,apiImportApp,apiExportApp ,apiExportBizType,apiExportModule} from '@/api/modules/EW.js'
  const route = useRoute()
  const menuShow = ref(false)
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'usersAudit'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const tableRef = ref(null)
  const activeName = ref('1')
  const importDiag = ref(false)
  const exclueValues = ref([])
  const tabsArr = ref([
    {
      label:'应用系统',
      id:'1',
    },
    {
      label:'业务模块',
      id:'2',
    },
    {
      label:'业务类型',
      id:'3',
    },
  ])
  const state = reactive({
    query: {
      appId:'',
      appCode:'',
      appName:'',
      
      moduleId:'',
      moduleCode:'',
      moduleName:'',
      biztypeId:'',
      biztypeCode:'',
      biztypeName:'',
      current: 1,
      size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const columns: Column[] = reactive([
    {
      label: '应用ID',
      prop: 'appId',
      align: 'center',
      editable: false,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '应用代码',
      prop: 'appCode',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '应用名称',
      prop: 'appName',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '前端地址',
      prop: 'appUrl',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '后端地址',
      prop: 'appBackendUrl',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '平台类型',
      prop: 'platType',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '备注',
      prop: 'remark',
      align: 'center',
      editable: true,
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },

    // {
    //   label: '',
    //   prop: 'action',
    //   actionConfig: [{ id: 'isTop', type: 'top' }],
    // },
  ])
  
  const checkedRows = ref([])
  const uploadFile = reactive({})
  const handleClick = (tab,e) =>{
    pageConfig.currentPage = 1
    state.query.current = 1
    if(tab.props.name == 1){
      exclueValues.value = ['biztypeCode','biztypeId','biztypeName','moduleCode','moduleId','moduleName']
      queryAppFunc()
    }else if(tab.props.name == 2){
      exclueValues.value = ['appCode','appName','biztypeCode','biztypeId','biztypeName']
      queryModuleFunc()
    }else if(tab.props.name == 3){
      exclueValues.value = ['appId','appName','moduleCode','moduleId','moduleName']
      queryBizTypeFunc()
    }
  }
  //导出
  const exportClick = (type) => {
    if(type == 'app') apiExportApp(state.query)
    if(type == 'module') apiExportModule(state.query)
    if(type == 'biz') apiExportBizType(state.query)
  }

//导入
const uploadFunc = (file) => {
  uploadFile.value = file
}
//点确定
const uploadSure = () =>{
  const list = toRaw(uploadFile.value)
  console.log(list.raw,'listlistlist')
  uploadApiFn(list.raw)
  
}
const uploadApiFn = (file) =>{
  console.log(file,'file78')
  let par = {
    file
  }
  apiImportApp(par)
    .then((res) => {
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch(() => {})
}
  //应用系统查询
  const queryAppFunc = () =>{
    apiQueryApp(state.query)
      .then((res) => {
        console.log(res, 'res')
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        } else {
          // ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  //业务模块查询
  const queryModuleFunc = () =>{
    apiQueryModule(state.query).then((res) => {
        console.log(res, 'res')
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  //业务类型查询
  const queryBizTypeFunc = () =>{
    apiQueryBizType(state.query).then((res) => {
        console.log(res, 'res')
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          pageConfig.pageSize = Number(res.data.data.size)
          pageConfig.total = Number(res.data.data.count)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  //删除事件
  const deleteRow = () => {
    if (!checkedRows.value.length) {
      useMessage().warning('请选择一条数据')
      return
    }
    let ids = []
    Array.isArray(checkedRows.value) &&
      checkedRows.value.forEach((item: any) => {
        if (item?.appId) ids.push(item?.appId)
      })
    isTableLoading.value = true
    apiDeleteApp({appId:ids})
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          useMessage().success(res.data.message)
          searchFn()
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
        isTableLoading.value = false
      })
    
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn('page')
  }
  
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
  
    if(type == 'page'){
      state.query.current = pageConfig.currentPage
    }else{
      pageConfig.currentPage = 1
      state.query.current = 1
    }
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    if(activeName.value == 1){
      queryAppFunc()
    }else if(activeName.value == 2){
      queryModuleFunc()
    }else if(activeName.value == 3){
      queryBizTypeFunc()
    }
    
  }
  const handleSave = () => {
    isTableLoading.value = true
    saveSuccessful.value = false
    apiSaveApp(checkedRows.value)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          // saveSuccessful.value = true
          tableRef.value.clearSelection()
          searchFn()
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  //   const exportRow = () => {
  //     apiGroupUserExport(state.query)
  //   }
  const ruleFormRef = ref(null)
  
  const addRowSave = (data) => {
    handleSave()
  }
  onMounted(() => {
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
    searchFn()
  })
  </script>
  <style lang="less" scoped></style>
  